package com.ukao.steward.ui.valetRunners.createOrder;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.jdsjlzx.ItemDecoration.DividerDecoration;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.ukao.steward.R;
import com.ukao.steward.adapter.CouponsAdapter;
import com.ukao.steward.base.BaseFragment;
import com.ukao.steward.bean.Coupons;
import com.ukao.steward.bean.StringBean;
import com.ukao.steward.consts.Constant;
import com.ukao.steward.consts.SaveParams;

import com.ukao.steward.retrofit.ApiCallback;
import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.util.L;
import com.ukao.steward.util.T;
import com.ukao.steward.widget.MyLRecyclerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import rx.Observable;

/**
 * 优惠券
 */
public class CouponFragment extends BaseFragment implements OnItemClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.back_btn)
    ImageView backBtn;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.title_layout)
    RelativeLayout titleLayout;
    @BindView(R.id.recycler_views)
    MyLRecyclerView recyclerViews;
    Unbinder unbinder;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private CouponsAdapter mCouponsAdapter;
    private List<Coupons> mCoupons = new ArrayList<>();
    private LRecyclerViewAdapter mLRecyclerViewAdapter;
    private String orderId;
    private   boolean  isUndeblocking=false;
    private  View view;
    private String couponId;

    public static CouponFragment newInstance(String orderId, String couponId) {
        CouponFragment fragment = new CouponFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, orderId);
        args.putString(ARG_PARAM2, couponId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            orderId = getArguments().getString(ARG_PARAM1);
            couponId= getArguments().getString(ARG_PARAM2);
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
         view = inflater.inflate(R.layout.fragment_coupon, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initListener();
    }

    @Override
    protected void initView() {
        titleLayout.setBackgroundColor(getColors(R.color.colorPrimary));
        title.setText("优惠券列表");
        DividerDecoration divider = new DividerDecoration.Builder(_mActivity)
                .setHeight(R.dimen.dp_10)
                .setColorResource(R.color.transparent)
                .build();
        View mEmptyView = view.findViewById(R.id.empty_view);
        recyclerViews.setEmptyView(mEmptyView);//设置在setAdapter之前才能生效
        initLinearRecyclerView(recyclerViews);
        mCouponsAdapter = new CouponsAdapter(_mActivity, mCoupons);
        mLRecyclerViewAdapter = new LRecyclerViewAdapter(mCouponsAdapter);
        recyclerViews.setAdapter(mLRecyclerViewAdapter);
        recyclerViews.addItemDecoration(divider);



    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        recyclerViews.forceToRefresh();
    }


    @Override
    protected void initListener() {
        super.initListener();
        mLRecyclerViewAdapter.setOnItemClickListener(this);
        recyclerViews.setOnRefreshListener(mOnRefreshListener);
    }


    private OnRefreshListener mOnRefreshListener = new OnRefreshListener() {
        @Override
        public void onRefresh() {
          if(!isUndeblocking){
              unlockOrder();
          }else{couponList();
          }


        }
    };


    /**
     * 使查询订单优惠券
     *
     *
     */
    public void couponList( ) {

        HashMap mHashMap = new HashMap<String, String>();
        mHashMap.put("orderId", orderId);
        mHashMap.put("accessToken", SaveParams.getToken());
        addSubscription(apiStores().couponList(Constant.createParameter(mHashMap)),
                new ApiCallback<Coupons>() {
                    @Override
                    public void onSuccess(Coupons model) {
                        if (model.getHttpCode() == 200) {
                            if (!CheckUtils.isEmpty(couponId)){
                                for (Coupons coupons : model.getData()) {
                                    Log.i("aini","coupons.getId().="+coupons.getId()+"couponId="+couponId);
                                    if (coupons.getId().equals(couponId)){
                                        coupons.setEnableUse(1);
                                        coupons.setCheck(true);
                                    }
                                }
                            }


                            mCouponsAdapter.setDataList(model.getData());



                        } else {
                            T.show(model.getMsg());

                        }

                    }


                    @Override
                    public void onFinish() {
                        recyclerViews.refreshFinish();

                    }

                });
    }
    /*支付解锁*/
    public void unlockOrder(      ) {
        HashMap mHashMap = new HashMap<String, String>();
        mHashMap.put("orderId", orderId);
        mHashMap.put("accessToken", SaveParams.getToken());
        addSubscription(apiStores().unlockOrder(Constant.createParameter(mHashMap)),
                new ApiCallback<StringBean>() {
                    @Override
                    public void onSuccess(StringBean model) {
                        if (model.getHttpCode() == 200) {
                            isUndeblocking=true;
                            couponList();

                        } else {

                            T.show(model.getMsg());
                        }

                    }


                    @Override
                    public void onFinish() {

                    }

                });
    }




    /**
     * @param isNoUsecoupon 是否取消优惠卷
     * @param
     */
    public void couponInfo(boolean isNoUsecoupon, final Coupons mitem,final int pos) {
        showProgressDialog();
        HashMap mHashMap = new HashMap<String, String>();
        mHashMap.put("accessToken", SaveParams.getToken());
        Observable observable = null;
        if (isNoUsecoupon) {
            mHashMap.put("orderId", orderId);
            observable = apiStores().canCouponInfo(Constant.createParameter(mHashMap));
        } else {
            mHashMap.put("orderId", orderId);
            mHashMap.put("relId", mitem.getId());/*订单优惠券id*/
            observable = apiStores().userCouponInfo(Constant.createParameter(mHashMap));
        }
        addSubscription(observable,
                new ApiCallback<StringBean>() {
                    @Override
                    public void onSuccess(StringBean model) {
                        if (model.getHttpCode() == 200) {
                            mitem.setCheck(!mitem.isCheck());
                            if (mitem.isCheck()){
                                List<Coupons> mData = mCouponsAdapter.getDataList();
                                for (int j = 0; j < mData.size(); j++) {
                                    if (pos != j) {
                                        mData.get(j).setCheck(false);

                                    }
                                }


                            }
                            mCouponsAdapter.notifyDataSetChanged();




                        } else {
                            T.show(model.getMsg());
                        }

                    }


                    @Override
                    public void onFinish() {
                    dismissProgressDialog();
                    }

                });
    }


    /**
     * 使用优惠券
     */
    public void userCouponInfo(final Coupons mCoupons) {
        showProgressDialog();
        HashMap mHashMap = new HashMap<String, String>();
        mHashMap.put("orderId", orderId);
        mHashMap.put("relId", mCoupons.getId());/*订单优惠券id*/
        mHashMap.put("accessToken", SaveParams.getToken());
        addSubscription(apiStores().userCouponInfo(Constant.createParameter(mHashMap)),
                new ApiCallback<StringBean>() {


                    @Override
                    public void onSuccess(StringBean model) {
                        if (model.getHttpCode() == 200) {
                            L.i(" mCoupons.getId()="+ mCoupons.getId());
                            Bundle mBundle = new Bundle();
                            mBundle.putInt(Constant.ARG_PARAM1, mCoupons.getAmount());
                            mBundle.putString(Constant.ARG_PARAM2, mCoupons.getId());
                            setFragmentResult(RESULT_OK, mBundle);
                            finish();


                        } else {
                            T.show(model.getMsg());

                        }

                    }


                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }

                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @OnClick({R.id.back_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                onBackPressedSupport();
                break;

        }
    }

    @Override
    public boolean onBackPressedSupport() {
        if (mCouponsAdapter!=null){
            List<Coupons> mData = mCouponsAdapter.getDataList();
            Coupons mCoupons=null;
            for (Coupons coupons : mData) {
                if (coupons.isCheck()){
                    mCoupons=coupons;

                }
            }

            Bundle mBundle = new Bundle();
            mBundle.putInt(Constant.ARG_PARAM1,mCoupons!=null? mCoupons.getAmount():0);
            mBundle.putString(Constant.ARG_PARAM2,mCoupons!=null? mCoupons.getId():"");
            setFragmentResult(RESULT_OK, mBundle);
            finish();

        }



        return true;

    }

    @Override
    public void onItemClick(View view, int position) {
        Coupons mItem = mCouponsAdapter.getItem(position);
        if (!CheckUtils.isNull(mItem)&&mItem.getEnableUse()) {
            couponInfo(mItem.isCheck(), mItem,position);
        }


    }
}
